package initcontroller

import (
	"context"
	"go-kube-mgr/config"
	"go-kube-mgr/utils/logs"
	corev1 "k8s.io/api/core/v1"
	metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
	"k8s.io/client-go/kubernetes"
	"k8s.io/client-go/tools/clientcmd"
)

// 检查namespace是否存在，从namespace里读取kubeconfig
func metadataInit() {
	logs.Debug(nil, "初始化元数据命名空间")
	restConfig, err := clientcmd.BuildConfigFromFlags("", "config/kubeconfig")
	if err != nil {
		logs.Error(map[string]interface{}{"msg": err.Error()}, "inCluster kubeconfig加载失败")
		panic(err.Error())
	}

	clientset, err := kubernetes.NewForConfig(restConfig)
	if err != nil {
		logs.Error(map[string]interface{}{"msg": err.Error()}, "inCluster客户端创建失败")
		panic(err.Error())
	}
	config.InClusterClientSet = clientset
	inClusterVersion, _ := clientset.Discovery().ServerVersion()

	_, err = clientset.CoreV1().Namespaces().Get(context.TODO(), config.MetadataNamespace, metav1.GetOptions{})
	if err != nil {
		// namespace不存在，新创建namespace
		logs.Info(nil, "元数据namespace不存在，准备创建")
		var metadataNamespace corev1.Namespace
		metadataNamespace.Name = config.MetadataNamespace
		_, err = clientset.CoreV1().Namespaces().Create(context.TODO(), &metadataNamespace, metav1.CreateOptions{})
		if err != nil {
			logs.Error(map[string]interface{}{"msg": err.Error()}, "元数据命名空间创建失败")
			panic(err.Error())
		}
		logs.Info(map[string]interface{}{"Namespace": config.MetadataNamespace, "inCluster版本": inClusterVersion.String()}, "元数据namespace创建成功")
		// 写入 kubeconfig
	} else {
		// namespace已存在
		logs.Info(map[string]interface{}{"Namespace": config.MetadataNamespace, "inCluster版本": inClusterVersion.String()}, "元数据namespace已经存在")
	}

	// 读取secret中的kubeconfig数据，存入config变量中
	listOptions := metav1.ListOptions{
		LabelSelector: config.ClusterConfigSecretLabelKey + "=" + config.ClusterConfigSecretLabelValue,
	}
	secretList, _ := config.InClusterClientSet.CoreV1().Secrets(config.MetadataNamespace).List(context.TODO(), listOptions)
	for _, secret := range secretList.Items {
		clusterId := secret.Name
		kubeconfig := secret.Data["kubeconfig"]
		config.ClusterKubeconfig[clusterId] = string(kubeconfig)
	}

}
